<?php


namespace Biz\service\advertisement\position;

use Biz\model\advertisement\MPositionAdType;
use Biz\service\admin\tools\SimplePageTpl;
use Biz\service\advertisement\position\dao\BizPositionManagementDao;
use Biz\service\advertisement\position\model\BizPositionManagementModel;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Exception;
use Illuminate\Http\Request;

class BizPositionPuckManagement extends BizPositionPageTpl
{
    const TPL_CONFIG_TPL_NAME = '占位后台配置';

    public function getList(): array
    {
        return MPositionAdType::select('*', MPositionAdType::$normalCondition);
    }

    public function getTotal(): int
    {
        return 0;
    }

    public function condition(): array
    {
        $tab = $this->getRequest()->input('tab', '');
        $condition = [];

        if ($tab) $condition['tab'] = $tab;

        return $condition;
    }



    public function getGrid(Grid $grid)
    {
        $grid->disableFilter();
        $grid->disablePagination();
        $grid->column('id', 'ID')->sort();
        $grid->column('type_name', '占位名称');
        $grid->column('bg_color', '背景色');
        $grid->column('position_config', '关联配置');
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
        });
    }

    public function getForm(Form $form)
    {
        $form->hidden('id');
        $form->text('type_name', '占位名称')->required();
        $form->color('bg_color', '背景色')->required();
        $form->text('position_config', '关联配置')->required();
    }

    public function getFormInfo($id): array
    {
        return MPositionAdType::getById($id);
    }

    /**
     * @throws Exception
     */
    public function save($input)
    {
        $id = $input['id'] ?? 0;
        $data = [
            'type_name' => $input['type_name'] ?? '',
            'bg_color' => $input['bg_color'] ?? '',
            'position_config' => $input['position_config'] ?? '',
        ];
        return $id > 0 ? MPositionAdType::update($data, ['id' => $id])->rowCount() : MPositionAdType::insert($data);
    }

    public function delete($id): int
    {
        return MPositionAdType::update(['type_status' => 9], ['id' => $id])->rowCount();
    }

    public function sort($input)
    {
        if ($input) {
            $max = count($input) + 1;
            foreach ($input as $id => $sort) {
                MPositionAdType::update(['sort' => $max - $sort], ['id' => $id]);
            }
        }
    }

}